import 'package:flutter_enjoy_plus_ghz/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Tokenmanager {
  String? _token; // 存储token的变量
  String? _refreshToken; // 存储refreshToken的变量
  // 获取存储的实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

//项目启动时进行初始化
  init() async {
    final instance = await _getInstance(); // 获取实例对象
    _token = instance.getString(GlobalVariable.TOKEN_KEY) ?? "";
    _refreshToken = instance.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? "";
  }

  // 存储token
  void setToken(String token, {String? refreshToken}) async {
    final instance = await _getInstance(); // 获取实例对象
    _token = token; // 设置token
    instance.setString(GlobalVariable.TOKEN_KEY, token);
    if (refreshToken != null) {
      _refreshToken = refreshToken; // 设置refreshToken
      instance.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken);
    }
  }

  // 获取token
  String getToken() {
    return _token ?? "";
  }

  // 获取refreshToken
  String getRefreshToken() {
    return _refreshToken ?? "";
  }

  // 删除token
  void removeToken() async {
    final instance = await _getInstance(); // 获取实例对象
    _token = null; // 设置token
    _refreshToken = null; // 设置refreshToken
    instance.remove(GlobalVariable.TOKEN_KEY);
    instance.remove(GlobalVariable.REFRESH_TOKEN_KEY);
  }
}

final tokenManager = Tokenmanager();
